<style lang="less" scoped>
@page {
  size: auto;
  margin: 3mm;
}
/* 进度条遮罩 */
.progress-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.6); /* 半透明黑色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999; /* 确保遮罩在最前面 */
}

/* 进度条样式 */
.progress-bar {
  width: 400px;
  background-color: #fff; /* 进度条背景白色 */
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
}
.cardiovascular-program {
  width: 100%;
  height: 100%;
  /deep/.el-table__inner-wrapper {
    height: 100% !important;
  }
  .shaixuan {
    display: flex;
    align-items: center;
    justify-content: end;
    background: #fff;
    padding: 5px;
    img {
      height: 20px;
    }
  }
  .fixed-box {
    position: fixed;
    width: 300px;
    height: 120px;
    bottom: 150px;
    z-index: 999;
    background-color: #fff;
    right: 50px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    box-shadow: 10px 10px 10px #ccc;
    border: 1px solid #eee;
    border-radius: 4px;
    .box-close {
      position: absolute;
      top: 10px;
      right: 10px;
      color: #666;
      cursor: pointer;
    }
    .box-title {
      font-size: 20px;
      line-height: 30px;
    }
    .box-num {
      font-size: 16px;
      line-height: 30px;
      span {
        font-size: 20px;
        color: #337ecc;
      }
    }
  }
  .box-img {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 300px;
    div {
      width: 48%;
      height: 100%;
    }
  }
  .pagination-css {
    padding: 5px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    justify-content: right;
    margin-top: 5px;
  }
}
</style>

<template>
  <div
    class="cardiovascular-program"
    v-loading.fullscreen.lock="fullscreenLoading"
  >
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline form-css"
    >
      <el-form-item label="关键字：">
        <el-input
          v-model="formInline.keyword"
          placeholder="请输入条码、姓名、设备名称"
        />
      </el-form-item>
      <el-form-item label="检查时间：">
        <el-date-picker
          v-model="formInline.inspectionTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="上传时间：">
        <el-date-picker
          v-model="formInline.uploadTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="项目点名称：">
        <el-select v-model="formInline.projectName" filterable placeholder="">
          <el-option v-for="(item, index) in projectList" :key="index" :label="item.insname" :value="item.insname" />
        </el-select>
        <!-- <el-input v-model="formInline.projectName" placeholder="" /> -->
      </el-form-item>
      <el-form-item label="报告状态：">
        <el-select v-model="formInline.reportStatus" placeholder="">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否有效：">
        <el-select v-model="formInline.isInvalid" placeholder="请选择">
          <el-option
            v-for="item in isUsedList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="诊断结论：">
        <el-input v-model="formInline.diagnosis" placeholder="" style="width: 228px;"></el-input>
      </el-form-item>
      <el-form-item label="是否阳性：">
        <el-select v-model="formInline.isPositive" placeholder="请选择">
          <el-option
            v-for="item in isPositiveList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="display: flex; align-items: center; flex-wrap: nowrap;width: 100%;">
        <el-button type="primary" @click="search"
          ><el-icon style="margin-right: 6px"><Search /></el-icon>
          搜索</el-button
        >
        <el-button @click="reset"
          ><el-icon style="margin-right: 6px"><Refresh /></el-icon>
          重置</el-button
        >
        <vue3-json-excel
          :fields="json_fields"
          :name="userExcelName"
          :fetch="downloadEx"
          style="margin-left: 12px"
        >
          <el-button>
            <!-- <el-icon style="margin-right: 6px"><Document /></el-icon> -->
            <img
              style="margin-right: 6px; width: 12px"
              src="@/images/daochu.png"
              alt="导出患者信息"
            />

            批量导出信息</el-button
          >
        </vue3-json-excel>
        <!-- <el-button type="primary"><el-icon><Document /></el-icon>导出</el-button> -->
        <el-button
          type="primary"
          :disabled="selectedItems.length === 0"
          style="margin-left: 12px"
          :style="{backgroundColor: selectedItems.length > 0 ? '#409EFF' : '#C0C4CC' }"
          @click="exportSelectedPDFs"
        >
        导出已选定的报告
        </el-button>
        <!-- 新增的批量导出全部报告按钮 11月7-->
        <el-button type="primary" style="margin-left: 12px" @click="exportAllPDFs">
          批量导出全部报告
        </el-button>
       <!-- 进度条背景遮罩  stroke-width="30" -->
    <div v-if="progressVisible" class="progress-mask">
      <el-progress 
        :percentage="progress" 
        :status="progressStatus"
        :text-inside="true"
        stroke-width="30"
        
        :format="progressFormat"
        class="progress-bar"
      />
    </div>
      </el-form-item>
    </el-form>
    <div class="filter-column">
      <el-popover
        placement="bottom"
        title="筛选条件"
        :width="150"
        trigger="click"
      >
        <el-checkbox-group v-model="filtrateList" @change="changeBox">
          <el-checkbox label="t_sn">条码</el-checkbox>
          <el-checkbox label="project">项目类型</el-checkbox>
          <el-checkbox label="insname">机构名称</el-checkbox>
          <el-checkbox label="name">姓名</el-checkbox>
          <el-checkbox label="sex">性别</el-checkbox>
          <el-checkbox label="age">年龄</el-checkbox>
          <el-checkbox label="isPositive">是否阳性</el-checkbox>
          <el-checkbox label="diagnosis">诊断结论</el-checkbox>
          <el-checkbox label="isInvalid">是否有效</el-checkbox>
          <el-checkbox label="invalidReason">无效原因</el-checkbox>
          <el-checkbox label="devname">设备名称</el-checkbox>
          <el-checkbox label="checkTime">检查时间</el-checkbox>
          <el-checkbox label="docname">检查医师</el-checkbox>
          <el-checkbox label="uploadTime">上传时间</el-checkbox>
          <el-checkbox label="auditstatus">报告状态</el-checkbox>
          <el-checkbox label="dicomurl">常规报告</el-checkbox>
          <el-checkbox label="upstat">国家报告</el-checkbox>
          <el-checkbox label="devid">设备SN</el-checkbox>
          <el-checkbox label="origins">登记机构</el-checkbox>
          <el-checkbox label="upstatus">上传状态</el-checkbox>
        </el-checkbox-group>
        <template #reference>
          <el-button type="text"
            ><div class="shaixuan">
              <img src="@/images/shaixuan.png" alt="" /> 筛选列
            </div></el-button
          >
        </template>
      </el-popover>
    </div>
    <el-table
      v-loading="tableLoading"
      :data="tableData"
      :header-cell-style="{ backgroundColor: '#EEF6FF' }"
      border
      height="calc(100% - 323px)"
      style="width: 100%; padding: 10px"
      @selection-change="handleSelectionChange"   
    >
    <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" width="50" align="center" />
      <el-table-column
        v-if="filtrateList.includes('t_sn')"
        prop="t_sn"
        min-width="120px"
        label="条码"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('project')"
        prop="project"
        min-width="120px"
        label="项目类型"
        align="center"
      />
      <!-- <el-table-column
        v-if="filtrateList.includes('insname') && $store.getters.name == 'admin'"
        prop="insname"
        min-width="200px"
        label="机构名称"
        align="center"
      >
        <template #default="scoped">
          <div v-if="!scoped.row.isEdit" @click="choseInsname(scoped.row, scoped.$index)" :style="{color: '#409eff', width: '175px', height: scoped.row.insname ? '100%' : '23px'}">{{ scoped.row.insname }}</div>
          <div v-else style="display: flex; align-items: center;">
            <el-select v-model="scoped.row.insname1" filterable placeholder="">
              <el-option v-for="(item, index) in projectList" :key="index" :label="item.insname" :value="item.insname" />
            </el-select>
            <span @click="submitInsname(scoped.row, scoped.$index)"><el-icon><Check /></el-icon></span>
            <span @click="scoped.row.isEdit = false"><el-icon><Close /></el-icon></span>
          </div>
        </template>
      </el-table-column> -->
      <el-table-column
        v-if="filtrateList.includes('insname')"
        prop="insname"
        min-width="200px"
        label="机构名称"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('name')"
        prop="name"
        min-width="84px"
        label="姓名"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('sex')"
        prop="sex"
        min-width="84px"
        label="性别"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('age')"
        prop="age"
        min-width="84px"
        label="年龄"
        align="center"
      >
        <template #default="{ row }">
          <span>{{ row.age == 0 ? "-" : row.age }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('isPositive')"
        prop="isPositive"
        min-width="160px"
        label="是否阳性"
        align="center"
      >
        <template #default="{ row }">
          <span>{{
            row.isPositive == "1" ? "阳性" : row.isPositive == "0" ? "阴性" : ""
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('diagnosis')"
        prop="diagnosis"
        min-width="160px"
        label="诊断结论"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('isInvalid')"
        prop="isInvalid"
        min-width="160px"
        label="是否有效"
        align="center"
      >
        <template #header>
          <el-popover
            placement="bottom-start"
            title="提示"
            :width="300"
            trigger="hover"
            content="“无效”表示扫查结果不合格，无法出具报告，需要重新扫查，请等待处理"
          >
            <template #reference>
              <span
                >是否有效<el-icon style="color: rgb(66, 206, 206)"
                  ><WarningFilled /></el-icon
              ></span>
            </template>
          </el-popover>
        </template>
        <template #default="{ row }">
          <span :style="{ color: row.isInvalid == '1' ? 'red' : '' }">{{
            row.isInvalid == 1 ? "无效" : "有效"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('invalidReason')"
        prop="invalidReason"
        min-width="120px"
        label="无效原因"
        align="center"
      />

      <el-table-column
        v-if="filtrateList.includes('devname')"
        prop="devname"
        min-width="120px"
        label="设备名称"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('auditstatus')"
        prop="auditstatus"
        min-width="84px"
        label="报告状态"
        align="center"
      >
        <template #default="{ row }">
          <span>{{
            row.auditstatus == 0
              ? "待审核"
              : row.auditstatus == 1
              ? "审核中"
              : row.auditstatus == 2
              ? "退回重审"
              : row.auditstatus == 10
              ? "已审核"
              : ""
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('dicomurl')"
        prop="dicomurl"
        min-width="185px"
        label="常规报告"
        align="center"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-button
            type="primary"
            text="primary"
            @click="regularInfo(row)"
            :style="{
              color:
                row.auditstatus == 10
                  ? row.dwncnt == 0
                    ? ''
                    : '#24ae24'
                  : '#ccc',
            }"
            >{{ row.dwncnt == 0 ? "下载" : "已下载" }}</el-button
          >
          <el-button
            type="primary"
            text="primary"
            @click="printInfo(row)"
            :style="{
              color:
                row.auditstatus == 10
                  ? row.prtcnt == 0
                    ? ''
                    : '#24ae24'
                  : '#ccc',
            }"
            >{{ row.prtcnt == 0 ? "打印" : "已打印" }}</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('upstat')"
        prop="upstat"
        min-width="84px"
        label="国家报告"
        align="center"
      >
        <template #default="{ row }">
          <span @click="nationalInfo(row)" style="cursor: pointer"
            ><el-icon
              ><Document
                :style="{
                  color: row.auditstatus == 10 ? '#409eff' : '#ccc',
                }" /></el-icon
          ></span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="filtrateList.includes('checkTime')"
        prop="checkTime"
        min-width="120px"
        label="检查时间"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('docname')"
        prop="docname"
        min-width="100px"
        label="检查医师"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('uploadTime')"
        prop="uploadTime"
        min-width="120px"
        label="上传时间"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('devid')"
        prop="devid"
        min-width="120px"
        label="设备SN"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('origins')"
        prop="origins"
        min-width="120px"
        label="登记机构"
        align="center"
      />
      <el-table-column
        v-if="filtrateList.includes('upstatus')"
        prop="upstat"
        min-width="120px"
        label="上传状态"
        align="center"
      >
        <template #default="{ row }">
          {{ row.upstat == 200 ? '上传成功' : '上传失败' }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="$store.getters.name == 'admin'"
        label="操作"
        align="center"
        min-width="90px"
      >
        <template #default="{ row }">
          <el-button
            type="primary"
            link
            @click="edit(row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="showBox" class="fixed-box">
      <div class="box-close" @click="showBox = false">X</div>
      <div class="box-title">本期审核次数剩余</div>
      <div class="box-num">
        <span>{{ residueCnt }}</span
        >次
      </div>
    </div>
    <el-pagination
      v-model:current-page="pageList.current"
      v-model:page-size="pageList.size"
      :page-sizes="[20, 40, 60, 80]"
      small="small"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageList.total"
      class="pagination-css"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      v-model="regularVisible"
      width="800px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <template #title>
        <span>{{ "常规报告" }}</span>
      </template>
      <!-- <template #title>
        <span>常规报告</span>
      </template>  11月7-->

      <div id="pdf-content" style="padding: 0 20px">
        <div
          style="
            width: 100%;
            text-align: center;
            font-size: 24px;
            display: inline-block;
            margin-bottom: 5px;
            font-weight: 800;
          "
        >
          {{ $store.getters.insname }}
        </div>
        <span
          style="
            width: 100%;
            text-align: center;
            display: inline-block;
            font-size: 16px;
            font-weight: 600;
          "
          >超声筛查报告单</span
        >
        <div style="height: 1px; background-color: #666; margin: 5px 0"></div>
        <el-form inline style="height: 108px;">
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名：">{{ regularObj.name }}</el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="性别：">{{ regularObj.sex }}</el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="年龄：">{{ regularObj.age }}岁</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请机构：">
                <!-- {{ regularObj.insname }} -->
                <span style="display: inline-block; line-height: 20px;">{{ regularObj.insname }}</span>

              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="患者ID：">{{
                regularObj.t_sn
              }}</el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检查部位：">{{ "颈动脉" }}</el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="height: 1px; background-color: #666; margin: 5px 0"></div>
        <div
          class="box-img"
          style="display: flex; justify-content: space-between"
        >
          <div style="width: 48%">
            <el-image
              style="width: 100%; height: 100%"
              :src="regularObj.screenshot1Url"
              fit="contain"
              :preview-src-list="[regularObj.screenshot1Url]"
            />
          </div>
          <div style="width: 48%">
            <el-image
              style="width: 100%; height: 100%"
              :src="regularObj.screenshot2Url"
              fit="contain"
              :preview-src-list="[regularObj.screenshot2Url]"
            />
          </div>
        </div>
        <div style="height: 3px; background-color: #666; margin: 5px 0"></div>
        <div class="box-totip" style="height: 378px;">
          <span
            style="
              font-size: 24px;
              font-weight: 600;
              display: inline-block;
              width: 100%;
            "
            >超声描述：</span
          >
          <div
            v-if="JSON.parse(regularObj.json).description"
            v-for="(item, index) in JSON.parse(
              regularObj.json
            ).description.split('；')"
            :key="index"
            style="font-size: 15px; font-weight: 600; margin: 5px 0"
          >
            {{ item }}
          </div>
          <span style="font-size: 24px; font-weight: 600">超声提示：</span>
          <div
            style="
              font-size: 15px;
              font-weight: 600;
              margin: 5px 0;
            "
          >
            {{
              JSON.parse(regularObj.json).summary
                ? JSON.parse(regularObj.json).summary
                : ""
            }}
          </div>

          <!-- <span>超声描述：</span>
          <div>{{ regularObj.json ? JSON.parse(regularObj.json).description ? JSON.parse(regularObj.json).description : '' : '' }}</div>
          <span>超声提示：</span>
          <div>{{ regularObj.impression ? regularObj.impression : '' }}</div> -->
        </div>
        <!-- <div style="font-size: 20px; font-weight: 600">其他信息：</div> -->
        <el-form inline>
          <el-row>
            <el-col :span="8">
              <el-form-item label="报告时间：">{{
                regularObj.reportTime2
              }}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检查医师：">{{
                regularObj.docname
              }}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="报告医师：">{{
                regularObj.auditname
              }}</el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="height: 3px; background-color: #666;"></div>
        <div style="font-size: 12px; font-weight: 400">
          告知：1、超声检查准确性受诸多因素影响，如患者自身因素(肥胖、气体干扰、准备不充分、不能配合、病变位置特殊、疾病所处不同阶段)，设备因素(仪器型号及性能不同,其图像质量和分辨率有差异)、检查者因素(超声结论是以国内外公认的影像特征为依据，不同检査者对超声影像的判读可能存在差异)等，此报告是影像检查结果，请以病理诊断或临床最后诊断为准，与本次检查相关的医疗活动应充分了解上述因素并与临床医生沟通。2、本报告仅作参考，不作为证明或诊断材料。3、本报告仅对本次检查数据有效。
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            v-if="regularObj.operateType == '下载'"
            @click="getPdf(regularObj)"
            >下载PDF文件并关闭窗口</el-button
          >
          <el-button
            v-if="regularObj.operateType == '打印'"
            v-print="printViewInfo"
            >打印</el-button
          >
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="nationalVisible"
      width="800px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <template #title>
        <span>{{ "颈动脉脑卒中项目" }}</span>
      </template>
      <table border="1" style="width: 100%; border-collapse: collapse">
        <tbody>
          <tr>
            <td colspan="1">检查时间</td>
            <td colspan="2">
              {{ regularObj.checkTime ? regularObj.checkTime : "" }}
            </td>
            <td colspan="2">检查人</td>
            <td colspan="3">
              {{ regularObj.docname ? regularObj.docname : "" }}
            </td>
            <td colspan="1">检查机构名称</td>
            <td colspan="3">
              {{ regularObj.insname ? regularObj.insname : "" }}
            </td>
          </tr>
          <tr>
            <td colspan="12">
              检查结果：
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).resultException
                    ? JSON.parse(regularObj.json).resultException == "0"
                      ? "全部正常"
                      : JSON.parse(regularObj.json).resultException == "1"
                      ? "任一部位有异常"
                      : ""
                    : ""
                  : ""
              }}
            </td>
          </tr>
          <tr align="center">
            <td rowspan="3" width="80px">异常类型</td>
            <td rowspan="3">异常项目</td>
            <td colspan="10">责任病灶部位（注：本节中“口”填写相应数字）</td>
          </tr>
          <tr align="center">
            <td colspan="5">左侧</td>
            <td colspan="5">右侧</td>
          </tr>
          <tr align="center">
            <td>颈总</td>
            <td>窦部</td>
            <td>颈内</td>
            <td>锁骨下动脉SA</td>
            <td>椎动脉VA</td>
            <td>颈总</td>
            <td>窦部</td>
            <td>颈内</td>
            <td>锁骨下动脉SA</td>
            <td>椎动脉VA</td>
          </tr>
          <tr align="center">
            <td>内膜IMT</td>
            <td>增厚(IMT≥1.0mm)(1=是, 0=否)</td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).intimaImtAacL
                    ? JSON.parse(regularObj.json).intimaImtAacL
                    : ""
                  : ""
              }}
            </td>
            <td>\</td>
            <td>\</td>
            <td>\</td>
            <td>\</td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).intimaImtAacR
                    ? JSON.parse(regularObj.json).intimaImtAacR
                    : ""
                  : ""
              }}
            </td>
            <td>\</td>
            <td>\</td>
            <td>\</td>
            <td>\</td>
          </tr>
          <tr>
            <td rowspan="4" align="center">斑块</td>
            <td align="center">数量</td>
            <td colspan="10" style="padding-left: 10px">
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).plaqueCount
                    ? JSON.parse(regularObj.json).plaqueCount == "0"
                      ? "无"
                      : JSON.parse(regularObj.json).plaqueCount == "1"
                      ? "单发"
                      : JSON.parse(regularObj.json).plaqueCount == "2"
                      ? "多发"
                      : ""
                    : ""
                  : ""
              }}
            </td>
          </tr>
          <tr>
            <td>形态(1=不规则, 0=规则){{ JSON.parse(regularObj.json).plaqueFormAacL }}</td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueFormAacL)
                    ? JSON.parse(regularObj.json).plaqueFormAacL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueFormSinusL)
                    ? JSON.parse(regularObj.json).plaqueFormSinusL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueFormIcaL)
                    ? JSON.parse(regularObj.json).plaqueFormIcaL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueFormSaL)
                    ? JSON.parse(regularObj.json).plaqueFormSaL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueFormVaL)
                    ? JSON.parse(regularObj.json).plaqueFormVaL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueFormAacR)
                    ? JSON.parse(regularObj.json).plaqueFormAacR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueFormSinusR)
                    ? JSON.parse(regularObj.json).plaqueFormSinusR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueFormIcaR)
                    ? JSON.parse(regularObj.json).plaqueFormIcaR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueFormSaR)
                    ? JSON.parse(regularObj.json).plaqueFormSaR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueFormVaR)
                    ? JSON.parse(regularObj.json).plaqueFormVaR
                    : ""
                  : ""
              }}
            </td>
          </tr>
          <tr>
            <td>溃疡(1=有, 0=无)</td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueUlcerAacL)
                    ? JSON.parse(regularObj.json).plaqueUlcerAacL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueUlcerSinusL)
                    ? JSON.parse(regularObj.json).plaqueUlcerSinusL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueUlcerIcaL)
                    ? JSON.parse(regularObj.json).plaqueUlcerIcaL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueUlcerSaL)
                    ? JSON.parse(regularObj.json).plaqueUlcerSaL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueUlcerVaL)
                    ? JSON.parse(regularObj.json).plaqueUlcerVaL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueUlcerAacR)
                    ? JSON.parse(regularObj.json).plaqueUlcerAacR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueUlcerSinusR)
                    ? JSON.parse(regularObj.json).plaqueUlcerSinusR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueUlcerIcaR)
                    ? JSON.parse(regularObj.json).plaqueUlcerIcaR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueUlcerSaR)
                    ? JSON.parse(regularObj.json).plaqueUlcerSaR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? String(JSON.parse(regularObj.json).plaqueUlcerVaR)
                    ? JSON.parse(regularObj.json).plaqueUlcerVaR
                    : ""
                  : ""
              }}
            </td>
          </tr>
          <tr>
            <td>回声(1=强回声，2=中等回声，3=低回声，4=混合回声)</td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).plaqueEchoAacL
                    ? JSON.parse(regularObj.json).plaqueEchoAacL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).plaqueEchoSinusL
                    ? JSON.parse(regularObj.json).plaqueEchoSinusL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).plaqueEchoIcaL
                    ? JSON.parse(regularObj.json).plaqueEchoIcaL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).plaqueEchoSaL
                    ? JSON.parse(regularObj.json).plaqueEchoSaL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).plaqueEchoVaL
                    ? JSON.parse(regularObj.json).plaqueEchoVaL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).plaqueEchoAacR
                    ? JSON.parse(regularObj.json).plaqueEchoAacR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).plaqueEchoSinusR
                    ? JSON.parse(regularObj.json).plaqueEchoSinusR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).plaqueEchoIcaR
                    ? JSON.parse(regularObj.json).plaqueEchoIcaR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).plaqueEchoSaR
                    ? JSON.parse(regularObj.json).plaqueEchoSaR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).plaqueEchoVaR
                    ? JSON.parse(regularObj.json).plaqueEchoVaR
                    : ""
                  : ""
              }}
            </td>
          </tr>
          <tr>
            <td>狭窄或闭塞</td>
            <td>狭窄率(0=无狭窄，1=1-49%，2=50-69%，3=70-99%，4=闭塞)</td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).stenosisRateAacL
                    ? JSON.parse(regularObj.json).stenosisRateAacL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).stenosisRateSinusL
                    ? JSON.parse(regularObj.json).stenosisRateSinusL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).stenosisRateIcaL
                    ? JSON.parse(regularObj.json).stenosisRateIcaL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).stenosisRateSaL
                    ? JSON.parse(regularObj.json).stenosisRateSaL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).stenosisRateVaL
                    ? JSON.parse(regularObj.json).stenosisRateVaL
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).stenosisRateAacR
                    ? JSON.parse(regularObj.json).stenosisRateAacR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).stenosisRateSinusR
                    ? JSON.parse(regularObj.json).stenosisRateSinusR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).stenosisRateIcaR
                    ? JSON.parse(regularObj.json).stenosisRateIcaR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).stenosisRateSaR
                    ? JSON.parse(regularObj.json).stenosisRateSaR
                    : ""
                  : ""
              }}
            </td>
            <td>
              {{
                regularObj.json
                  ? JSON.parse(regularObj.json).stenosisRateVaR
                    ? JSON.parse(regularObj.json).stenosisRateVaR
                    : ""
                  : ""
              }}
            </td>
          </tr>
        </tbody>
      </table>
      <div>
        注:①内中膜厚度为最厚测的测值；②斑块为最大斑块的测量值；③斑块数量中，一个斑块定义为单发，2个或2个以上定义为多发；④狭窄率为面积狭窄率
      </div>
    </el-dialog>
    <el-dialog
      v-model="infoVisible"
      width="800px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <template #title>
        <span>{{ "患者信息" }}</span>
      </template>
      <el-form inline label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="条码：">
              <el-input v-model="patientForm.t_sn" disabled placeholder="请输入" style="width: 200px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构名称：">
              <el-select v-model="patientForm.insname" filterable placeholder="" style="width: 200px;">
                <el-option v-for="(item, index) in projectList" :key="index" :label="item.insname" :value="item.insname" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名：">
              <el-input v-model="patientForm.name" placeholder="请输入" style="width: 200px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别：">
              <el-select v-model="patientForm.sex" placeholder="" style="width: 200px;">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="年龄：">
              <el-input v-model="patientForm.age" placeholder="请输入" style="width: 200px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检查医师：">
              <el-input v-model="patientForm.docname" placeholder="请输入" style="width: 200px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系方式：">
              <el-input v-model="patientForm.tel" placeholder="请输入" style="width: 200px;" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="infoVisible = false">取消</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getUltraSoundList } from "@/apis/reportReview";
import format from "@/utils/format";
import { prtsn } from "@/apis/user";
import { getSubIns, getAllSubIns } from "@/apis/hospitalManagement";
import ExportSavePdf from "@/utils/html2pdf";
import { ElMessage } from "element-plus";
import JSZip from "jszip";
import { saveAs } from 'file-saver';
import { updateUltraIns, getContractNum } from "@/apis/reportList";

export default {
  data() {
    let _this = this;
    let nowTime = new Date().getTime();
    let stime = format(nowTime, "YYYY-MM-DD") + " " + "23:59:59";
    let etime = format(nowTime, "YYYY-MM-DD") + " " + "00:00:00";
    return {
      infoVisible: false,
      patientForm: null,
      residueCnt: 0,
      projectList: [],
      hosProps: {
        lazy: true,
        checkStrictly: true,
        label: "insname",
        value: "insname",
        lazyLoad(node, resolve) {
          _this.getJunior(node, resolve);
        },
      },
      insnameProps: {
        lazy: true,
        checkStrictly: true,
        label: "insname",
        value: "inscode",
        lazyLoad(node, resolve) {
          _this.getJunior(node, resolve);
        },
      },
      selectedItems: [], // 保存用户勾选的项目 9月25
      progress: 0, // 下载进度9月25
      progressVisible: false, // 进度条是否可见9月25
      progressStatus: "success", // 进度条状态9月25
      fullscreenLoading: false,
      printViewInfo: {
        id: "pdf-content", //打印区域的唯一的id属性
        popTitle: "", // 页眉文字 （不设置时显示undifined）（页眉页脚可以在打印页面的更多设置的选项中取消勾选）
        extraHead: "", // 最左上方的头部文字，附加在head标签上的额外标签，使用逗号分割
        preview: false, // 是否启动预览模式，默认是false （开启预览模式ture会占满整个屏幕，不建议开启，除非业务需要）
        previewTitle: "预览的标题", // 打印预览的标题(预览模式preview为true时才显示)
        previewPrintBtnLabel: "预览结束，开始打印", // 打印预览的标题下方的按钮文本，点击可进入打印(预览模式preview为true时才显示)
        zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
        previewBeforeOpenCallback(that) {
          console.log("正在加载预览窗口！");
          console.log(that.msg, this);
        }, // 预览窗口打开之前的callback (预览模式preview为true时才执行) （that可以取到data里的变量值）
        previewOpenCallback() {
          console.log("已经加载完预览窗口，预览打开了！");
        }, // 预览窗口打开时的callback (预览模式preview为true时才执行)
        beforeOpenCallback() {
          console.log("开始打印之前！");
        }, // 开始打印之前的callback
        openCallback() {
          console.log("执行打印了！");
        }, // 调用打印时的callback
        closeCallback() {
          _this.isPrint();
        }, // 关闭打印的callback(无法区分确认or取消)
        clickMounted() {
          console.log("点击v-print绑定的按钮了！");
        },
        // url: 'http://localhost:8080/', // 打印指定的URL，确保同源策略相同
        // asyncUrl (reslove) {
        //   setTimeout(() => {
        //     reslove('http://localhost:8080/')
        //   }, 2000)
        // },
        standard: "",
        extarCss: "",
      },
      json_fields: {
        序号: {
          field: "index",
          callback: (value) => {
            return String(value);
          },
        },
        条码: {
          field: "t_sn",
          callback: (value) => {
            return String(value);
          },
        },
        项目类型: {
          field: "project",
          callback: (value) => {
            return String(value);
          },
        },
        项目点名称: {
          field: "insname",
          callback: (value) => {
            return String(value);
          },
        },
        姓名: {
          field: "name",
          callback: (value) => {
            return String(value);
          },
        },
        性别: {
          field: "sex",
          callback: (value) => {
            return String(value);
          },
        },
        年龄: {
          field: "age",
          callback: (value) => {
            return String(value);
          },
        },
        是否阳性: {
          field: "isPositiveText",
          callback: (value) => {
            return String(value);
          },
        },
        是否有效: {
          field: "isInvalidText",
          callback: (value) => {
            return String(value);
          },
        },
        无效原因: {
          field: "invalidReason",
          callback: (value) => {
            return String(value);
          },
        },

        设备名称: {
          field: "devname",
          callback: (value) => {
            return String(value);
          },
        },
        报告状态: {
          field: "auditText",
          callback: (value) => {
            return String(value);
          },
        },
        检查时间: {
          field: "checkTime",
          callback: (value) => {
            return String(value);
          },
        },

        检查医师: {
          field: "docname",
          callback: (value) => {
            return String(value);
          },
        },
        上传时间: {
          field: "uploadTime",
          callback: (value) => {
            return String(value);
          },
        },
        设备SN: {
          field: "devid",
          callback: (value) => {
            return String(value);
          },
        },
        上传状态: {
          field: "upstatus",
          callback: (value) => {
            return String(value);
          },
        },
      },
      userExcelName: "",
      showBox: true,
      tableLoading: false,
      filtrateList: [
        "t_sn",
        "project",
        "devid",
        "devname",
        "name",
        "sex",
        "age",
        "isInvalid",
        "diagnosis",
        "isPositive",
        "invalidReason",
        "checkTime",
        "insname",
        "docname",
        "uploadTime",
        "auditstatus",
        "dicomurl",
        "upstat",
        "origins",
        "upstatus"
      ],
      formInline: {
        keyword: "",
        inspectionTime: [stime, etime],
        uploadTime: [],
        projectName: "",
        reportStatus: "",
        isInvalid: "",
        diagnosis: "",
        isPositive: "",
      },
      tableData: [],
      downloadedItemIds: new Set(), // 用于保存已下载的项目 ID
      selectedItems: [], // 保存用户勾选的项目
      downloadedFiles: [], // 已经下载成功的文件名列表
      tableLoading: false,
      selectedRows: [], // 选中的行数据9月25号
      pageList: {
        current: 1,
        size: 20,
        total: 0,
      },
      statusList: [
        {
          label: "待审核",
          value: "0",
        },
        {
          label: "审核中",
          value: "1",
        },
        {
          label: "退回重审",
          value: "2",
        },
        {
          label: "已审核",
          value: "10",
        },
      ],
      regularVisible: false,
      nationalVisible: false,
      regularObj: {},
      isUsedList: [
        {
          label: "无效",
          value: "1",
        },
        {
          label: "有效",
          value: "0",
        },
      ],
      isPositiveList: [
        {
          label: "阳性",
          value: "1",
        },
        {
          label: "阴性",
          value: "0",
        },
      ],
    };
  },
  mounted() {
    this.getTableData();//9月25号增加的这行
    let echCerebrovascularProjectPoint = localStorage.getItem(
      "echCerebrovascularProjectPoint"
    );
    if (echCerebrovascularProjectPoint) {
      this.filtrateList = JSON.parse(echCerebrovascularProjectPoint);
    }
    this.init();
    this.saveCookie();
    this.getJunior()
    this.getCnt()
  },
  methods: {
    edit(row) {
      this.patientForm = row
      console.log(row, 'row')
      console.log(this.patientForm, 'patientForm')
      this.infoVisible = true
    },
    submit() {
      console.log(this.patientForm, 'this.patientForm')
      let hospitalInfo = []
      if (this.patientForm.inscode) {
        hospitalInfo = this.projectList.filter(item => {
          return item.inscode == this.patientForm.inscode
        })
      }
      if (hospitalInfo.length > 0) {
        this.patientForm.insname = hospitalInfo[0].insname
      }
      updateUltraIns({
        uname: this.$store.getters.rname,
        inscode: this.$store.getters.inscode,
        data: JSON.stringify(this.patientForm),
      }).then(res => {
        if (res.code == 0) {
          ElMessage({
            message: '编辑成功！',
            type: 'success',
          });
          this.getTableData()
        } else {
          ElMessage({
            message: res.error,
            type: 'error',
          });
        }
        this.infoVisible = false
      })
    },
    getCnt() {
      this.residueCnt = 0
      getContractNum({
        uname: this.$store.getters.name,
        inscode: this.$store.getters.inscode,
      }).then(res => {
        if (res.code == 0) {
          if (res.data) {
            this.residueCnt = res.data.total_num
          }
        }
      })
    },
    getJunior() {
      this.projectList = []
      getAllSubIns({
        uname: this.$store.getters.name,
        inscode: this.$store.getters.inscode,
        subins: '',
      }).then((res) => {
        if (res.code == 0) {
          if (res.data && res.data.length > 0) {
            this.projectList = res.data
          }
        }
      });
    },
    // 通过代理下载 PDF 文件11月7
    fetchPDFThroughProxy(url) {
      const baseURL = "http://cvd.cdhyhs.com/pdf/";
      const cleanUrl = url.replace("https://ultrasound.cdhyhs.com/", "");
        // const proxyUrl = baseURL + cleanUrl;
        const proxyUrl = url;

      return fetch(proxyUrl)
        .then((response) => {
          if (!response.ok) {
            throw new Error("Network response was not ok");
          }
          return response.blob();
        })
        .catch((error) => {
          console.error("Error fetching PDF:", error);
          throw error;
        });
    },
    // 检查报告时间是否已选择11月7
  isReportTimeSelected() {
    return (
      this.formInline.uploadTime &&
      this.formInline.uploadTime.length > 0 &&
      this.formInline.uploadTime[0] &&
      this.formInline.uploadTime[1]
    );
  },
    saveCookie() {
      let echCerebrovascularProjectPoint = JSON.stringify(this.filtrateList);
      localStorage.setItem(
        "echCerebrovascularProjectPoint",
        echCerebrovascularProjectPoint
      );
    },
    changeBox() {
      let echCerebrovascularProjectPoint = JSON.stringify(this.filtrateList);
      localStorage.setItem(
        "echCerebrovascularProjectPoint",
        echCerebrovascularProjectPoint
      );
    },
    isPrint() {
      prtsn({
        type: "ultrasound",
        action: "print",
        sn: this.regularObj.t_sn,
        uname: this.$store.getters.name,
      }).then((res) => {
        if (res.data.status == "00") {
          this.init();
        }
      });
    },
    isDwn() {
      prtsn({
        type: "ultrasound",
        action: "download",
        sn: this.regularObj.t_sn,
        uname: this.$store.getters.name,
      }).then((res) => {
        if (res.data.status == "00") {
          this.init();
        }
      });
    },
    getPdf(regularObj) {
      let pdfTitle =
        (regularObj.t_sn ? regularObj.t_sn : "") +
        (regularObj.name ? regularObj.name : "");
      ExportSavePdf("pdf-content", pdfTitle, "");
      this.regularVisible = false;
      this.isDwn();
    },
    // 点击常规报告下载
    regularInfo(row) {
      if (row.auditstatus == 10) {
        console.log(row, "row");
        row.operateType = "下载";
        this.regularObj = {};
        this.regularObj = row;
        this.regularVisible = true;
      } else {
        ElMessage({
          type: "warning",
          message: "报告未审核，请等待审核通过后查看",
        });
      }
    },
    // 点击常规报告打印
    printInfo(row) {
      if (row.auditstatus == 10) {
        console.log(row, "row");
        row.operateType = "打印";
        this.regularObj = {};
        this.regularObj = row;
        this.regularVisible = true;
      } else {
        ElMessage({
          type: "warning",
          message: "报告未审核，请等待审核通过后查看",
        });
      }
    },
    // 点击国家报告
    nationalInfo(row) {
      if (row.auditstatus == 10) {
        console.log(row, "row");
        console.log(row.json, "json");
        console.log(JSON.parse(row.json), "parse");
        this.regularObj = {};
        this.regularObj = row;
        this.nationalVisible = true;
      } else {
        ElMessage({
          type: "warning",
          message: "报告未审核，请等待审核通过后查看",
        });
      }
    },
    async downloadEx() {
      let insTitle = this.$store.getters.insname
        ? this.$store.getters.insname
        : "";
      let inspecSTime = "";
      let inspecETime = "";
      let data = [];
      this.fullscreenLoading = true;
      if (
        this.formInline.inspectionTime &&
        this.formInline.inspectionTime.length > 0
      ) {
        inspecSTime = this.formInline.inspectionTime[0];
        inspecETime = this.formInline.inspectionTime[1];
        this.userExcelName =
          insTitle + "_超声报告列表_" + inspecSTime + "~" + inspecETime;
        let res = await getUltraSoundList({
          page: 1, // 当前页
          size: 10000, // 每页size
          uname: this.$store.getters.name, // 登录用户
          insname: this.$store.getters.insname, //用户机构名
          keyword: this.formInline.keyword ? this.formInline.keyword : "", // 关键字
          inspectionStime: this.formInline.inspectionTime
            ? this.formInline.inspectionTime[0]
              ? this.formInline.inspectionTime[0]
              : ""
            : "", // 检查开始时间
          inspectionEtime: this.formInline.inspectionTime
            ? this.formInline.inspectionTime[1]
              ? this.formInline.inspectionTime[1]
              : ""
            : "", // 检查结束时间
          uploadStime: this.formInline.uploadTime
            ? this.formInline.uploadTime[0]
              ? this.formInline.uploadTime[0]
              : ""
            : "", //上传开始时间
          uploadEtime: this.formInline.uploadTime
            ? this.formInline.uploadTime[1]
              ? this.formInline.uploadTime[1]
              : ""
            : "", //上传结束时间
          reportStime: this.formInline.reportTime
            ? this.formInline.reportTime[0]
              ? this.formInline.reportTime[0]
              : ""
            : "", //报告开始时间
          reportEtime: this.formInline.reportTime
            ? this.formInline.reportTime[1]
              ? this.formInline.reportTime[1]
              : ""
            : "", //报告结束时间
          projectName: this.formInline.projectName, //项目点名称
          auditorName: '', //审核机构名称
          auditorDoctor: this.formInline.auditorDoctor
            ? this.formInline.auditorDoctor
            : "", //审核医师
          reportStatus: this.formInline.reportStatus
            ? this.formInline.reportStatus
            : "", //报告状态
          project: "脑卒中",
          isInvalid: this.formInline.isInvalid,
          isPositive: this.formInline.isPositive,
          diagnosis: this.formInline.diagnosis,
        });
        console.log(res, "res");
        if (res.code == 0) {
          if (res.data && res.data.length > 0) {
            res.data.forEach((el, index) => {
              let auditText = "";
              el.index = index + 1;
              el.upstatus = ''
              if (el.upstat == 200) {
                el.upstatus = '上传成功'
              } else {
                el.upstatus = '上传失败'
              }
              if (el.auditstatus == 0) {
                auditText = "待审核";
              } else if (el.auditstatus == 1) {
                auditText = "审核中";
              } else if (el.auditstatus == 2) {
                auditText = "退回重审";
              } else if (el.auditstatus == 10) {
                auditText = "已审核";
              }
              el.auditText = auditText;
              el.isInvalidText = el.isInvalid == 0 ? "有效" : "无效";
              el.isPositiveText =
                el.isPositive == "1"
                  ? "阳性"
                  : el.isPositive == "0"
                  ? "阴性"
                  : "";

              el.checkTime = format(el.checkTime * 1000, "YYYY-MM-DD HH:mm:ss");
              el.uploadTime = format(
                el.uploadTime * 1000,
                "YYYY-MM-DD HH:mm:ss"
              );
              el.audittm = format(el.audittm * 1000, "YYYY-MM-DD");
              el.reportTime2 = format(el.reportTime * 1000, "YYYY-MM-DD");
            });
            data = res.data;
          }
        }
        this.fullscreenLoading = false;
        return data;
      } else {
        ElMessage({
          message: "请选择检查时间",
          type: "warning",
        });
        this.fullscreenLoading = false;
        return data;
      }
    },
    init() {
      this.getTableData();
    },
    getTableData() {
      this.tableData = [];
      this.tableLoading = true;
      getUltraSoundList({
        page: this.pageList.current, // 当前页
        size: this.pageList.size, // 每页size
        uname: this.$store.getters.name, // 登录用户
        insname: this.$store.getters.insname, //用户机构名
        keyword: this.formInline.keyword ? this.formInline.keyword : "", // 关键字
        inspectionStime: this.formInline.inspectionTime
          ? this.formInline.inspectionTime[0]
            ? this.formInline.inspectionTime[0]
            : ""
          : "", // 检查开始时间
        inspectionEtime: this.formInline.inspectionTime
          ? this.formInline.inspectionTime[1]
            ? this.formInline.inspectionTime[1]
            : ""
          : "", // 检查结束时间
        uploadStime: this.formInline.uploadTime
          ? this.formInline.uploadTime[0]
            ? this.formInline.uploadTime[0]
            : ""
          : "", //上传开始时间
        uploadEtime: this.formInline.uploadTime
          ? this.formInline.uploadTime[1]
            ? this.formInline.uploadTime[1]
            : ""
          : "", //上传结束时间
        reportStime: this.formInline.reportTime
          ? this.formInline.reportTime[0]
            ? this.formInline.reportTime[0]
            : ""
          : "", //报告开始时间
        reportEtime: this.formInline.reportTime
          ? this.formInline.reportTime[1]
            ? this.formInline.reportTime[1]
            : ""
          : "", //报告结束时间
        projectName: this.formInline.projectName, //项目点名称
        auditorName: this.formInline.auditorName
          ? this.formInline.auditorName
          : "", //审核机构名称
        auditorDoctor: this.formInline.auditorDoctor
          ? this.formInline.auditorDoctor
          : "", //审核医师
        reportStatus: this.formInline.reportStatus
          ? this.formInline.reportStatus
          : "", //报告状态
        project: "脑卒中",
        isInvalid: this.formInline.isInvalid,
        isPositive: this.formInline.isPositive,
        diagnosis: this.formInline.diagnosis,
      }).then((res) => {
        if (res.code == 0) {
          if (res.data && res.data.length > 0) {
            res.data.forEach((el) => {
              el.isEdit = false
              el.checkTime = format(el.checkTime * 1000, "YYYY-MM-DD HH:mm:ss");
              el.uploadTime = format(
                el.uploadTime * 1000,
                "YYYY-MM-DD HH:mm:ss"
              );
              el.audittm = format(el.audittm * 1000, "YYYY-MM-DD");
              el.reportTime2 = format(el.reportTime * 1000, "YYYY-MM-DD");
            });
            this.tableData = res.data;
            this.pageList.total = res.size;
            this.restoreDownloadStatus(); // 恢复下载状态11月7
          }
          this.tableLoading = false;
        }
      });
    },
    // 搜索
    search() {
      this.pageList.current = 1;
      this.getTableData();
    },
    // 重置
    reset() {
      let nowTime = new Date().getTime();
      let stime = format(nowTime, "YYYY-MM-DD") + " " + "23:59:59";
      let etime = format(nowTime, "YYYY-MM-DD") + " " + "00:00:00";
      this.formInline.keyword = "";
      this.formInline.inspectionTime = [stime, etime];
      this.formInline.uploadTime = [];
      this.formInline.reportTime = [];
      this.formInline.projectName = "";
      this.formInline.isInvalid = "";
      this.formInline.isPositive = "";
      this.formInline.diagnosis = "";
      this.formInline.reportStatus = "";
      this.pageList.current = 1;
      this.pageList.size = 20;
      // this.getTableData();
      this.init();
      //9月25号增加下面2行
      this.pageList.current = 1;
      this.getTableData();
    },
    handleSizeChange(val) {
      this.pageList.current = 1;
      this.pageList.size = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.pageList.current = val;
      this.getTableData();
    },
// ---------------- 通用的 PDF 下载和导出逻辑 ----------------10月20号
// ---------------- 加载和保存已下载文件的逻辑 ----------------
loadDownloadedFiles() {
      // 从 localStorage 加载已下载的文件列表
      const downloaded = localStorage.getItem('downloadedFiles');
      if (downloaded) {
        this.downloadedFiles = JSON.parse(downloaded);
      }
    },

    saveDownloadedFiles() {
      // 保存下载成功的文件列表到 localStorage
      localStorage.setItem('downloadedFiles', JSON.stringify(this.downloadedFiles));
    },
// 处理用户勾选的项目
    handleSelectionChange(val) {
      this.selectedItems = val;
    },
    async downloadAndExportPDFs(items) {
      const zip = new JSZip();
      const validItems = items.filter((item) => item.isInvalid === "0");
      if (validItems.length === 0) {
        this.$message.warning("没有有效报告可供下载");
        return;
      }

      // this.progress = 0;
      
      // this.progressVisible = true;
      // this.progressStatus = "active";
      const totalItems = validItems.length;
      let completedItems = 0;
      this.progressStatus = "active";
      this.progressVisible = true; // 保持进度条显示
      try {
    for (const item of validItems) {
      const pdfFileName = `${item.name}_${item.t_sn}.pdf`;

      try {
        const pdfBlob = await this.fetchPDFThroughProxy(item.pdfUrl);
        if (pdfBlob) {
          zip.file(pdfFileName, pdfBlob);
          item.dwncnt = 1; // 设置为已下载状态
          this.addDownloadedItem(item.t_sn); // 将下载项保存到 localStorage
        }
          // 更新进度条，每完成一个文件下载，更新进度
      completedItems++;
      this.progress = Math.floor((completedItems / totalItems) * 100);
      } catch (error) {
        console.error(`Failed to download ${pdfFileName}:`, error);
      }
    }

    // 当所有文件下载完成后，生成ZIP文件并保存
    const currentDate = format(new Date(), "YYYY-MM-DD");
    const zipFileName = `脑卒中超声报告_${validItems.length}份_${currentDate}.zip`;

    const blob = await zip.generateAsync({ type: "blob" });
    saveAs(blob, zipFileName);

    this.progressStatus = "success"; // 设置进度条状态为成功
  } catch (error) {
    console.error("批量导出失败", error);
    this.$message.error("导出过程中出错，请稍后重试");
    this.progressStatus = "exception";
  } finally {
    // 确保在下载过程完成后，再隐藏进度条
    setTimeout(() => {
      this.progressVisible = false;
    }, 500); // 延迟500ms后隐藏进度条，给用户视觉反馈
  }
},


    // 通过代理下载 PDF 文件
    fetchPDFThroughProxy(url) {
      const baseURL = "http://cvd.cdhyhs.com/pdf/";
      const cleanUrl = url.replace("https://ultrasound.cdhyhs.com/", "");
        // const proxyUrl = baseURL + cleanUrl;
        const proxyUrl = url;

      return fetch(proxyUrl)
        .then((response) => {
          if (!response.ok) {
            throw new Error("Network response was not ok");
          }
          return response.blob();
        })
        .catch((error) => {
          console.error("Error fetching PDF:", error);
          throw error;
        });
    },

    // ---------------- 已选定项目的导出 ----------------
    exportSelectedPDFs() {
      if (this.selectedItems.length === 0) {
        this.$message.warning("请先选择要导出的报告");
        return;
      }
      this.downloadAndExportPDFs(this.selectedItems);
    },

    // ---------------- 批量导出所有报告的功能 ----------------
    // async exportAllPDFs() {
    //   // 检查是否选择了报告时间
    // if (!this.isReportTimeSelected()) {
    //   this.$message.warning("未选择报告时间，请选择时间后再尝试导出");
    //   return; // 停止导出操作
    // }
    //   this.progressVisible = true; // 显示进度条
    //   let allItems = [];

    //   const pageSize = 100; // 每页请求的数据数量
    //   let currentPage = 1;
    //   let totalPages = 1;

    //   try {
    //     // 获取第一页数据并确定总页数
    //     const firstPage = await this.getUltraSoundData(currentPage, pageSize);
    //     if (!firstPage || !firstPage.data) {
    //   throw new Error("第一页数据无效或空");
    // }
    //     allItems.push(...firstPage.data);
    //     totalPages = Math.ceil(firstPage.total / pageSize);

    //     // 获取其余页的数据
    //     while (currentPage < totalPages) {
    //       currentPage++;
    //       await new Promise(resolve => setTimeout(resolve, 200)); // 延时200ms
    //       const pageData = await this.getUltraSoundData(currentPage, pageSize);
    //       if (pageData && pageData.data) {
    //     allItems.push(...pageData.data);
    //   } else {
    //     console.warn(`第 ${currentPage} 页数据为空或无效`);
    //   }
    //       // allItems.push(...pageData.data);

    //       // 更新进度条
    //       this.progress = Math.floor((currentPage / totalPages) * 100);
    //     }
    //      if (allItems.length === 0) {
    //   this.$message.warning("没有有效报告可供下载");
    //   this.progressVisible = false;
    //   return;
    // }
    //     // 导出所有数据
    //     this.downloadAndExportPDFs(allItems);
    //   } catch (error) {
    //     console.error("获取所有报告数据时出错:", error);
    //     this.$message.error("批量导出失败");
    //     this.progressStatus = "exception";
    //     this.progressVisible = false;
    //   }
    // },
    

    // // 获取每页的超声报告数据
    // async getUltraSoundData(page, size) {
    //   const res = await getUltraSoundList({
    //     page: page,
    //     size: size,
    //     uname: this.$store.getters.name,
    //     insname: this.$store.getters.insname,
    //     // reportStime: this.formInline.reportTime[0],
    //     // reportEtime: this.formInline.reportTime[1],
    //     uploadStime: this.formInline.uploadTime[0],
    //     uploadEtime: this.formInline.uploadTime[1],
    //     projectName: this.formInline.projectName,
    //     inspectDoctor: this.formInline.inspectDoctor,
    //     reportDoctor: this.formInline.reportDoctor,
    //     reportStatus: this.formInline.reportStatus,
    //     project: "心血管",
    //   });

    //   if (res.code === 0) {
    //     return res;
    //   } else {
    //     throw new Error("获取数据失败");
    //   }
    // },
//     async getUltraSoundData(page, size) {
//   try {
//     const res = await getUltraSoundList({
//       page: page,
//       size: size,
//       uname: this.$store.getters.name,
//       insname: this.$store.getters.insname,
//       uploadStime: this.formInline.uploadTime[0],
//       uploadEtime: this.formInline.uploadTime[1],
//       projectName: this.formInline.projectName,
//       inspectDoctor: this.formInline.inspectDoctor,
//       reportDoctor: this.formInline.reportDoctor,
//       reportStatus: this.formInline.reportStatus,
//       project: "心血管",
//     });

//     if (res.code === 0 && res.data) {
//       return res;
//     } else {
//       console.warn(`第 ${page} 页数据无效或返回错误`);
//       return { data: [] }; // 返回空数组以防止后续处理出错
//     }
//   } catch (error) {
//     console.error("获取数据失败:", error);
//     return { data: [] }; // 确保始终返回一致的数据结构
//   }
// },
async exportAllPDFs() {
  if (!this.isReportTimeSelected()) {
    this.$message.warning("未选择报告时间，请选择时间后再尝试导出");
    return;
  }

  this.progressVisible = true; // 显示进度条
  this.progressStatus = "active"; // 设置进度条为活动状态11月7
  this.progress = 0; // 初始化进度条
  
  let allItems = [];
  const pageSize = 100; // 每页请求的数据数量
  let currentPage = 1;
  let totalPages = 1;

  try {
   // 将项目点名称转换为字符串并进行 URL 编码
    const projectNameValue = Array.isArray(this.formInline.projectName) 
       ? this.formInline.projectName.join('/')  // 不进行URL编码
        : this.formInline.projectName;

    // 将搜索条件保存到 searchParams 中
    const searchParams = {
      uname: this.$store.getters.name,
      insname: this.$store.getters.insname,
      keyword: this.formInline.keyword,
      inspectionTimeStart: this.formInline.inspectionTime ? this.formInline.inspectionTime[0] : null,
      inspectionTimeEnd: this.formInline.inspectionTime ? this.formInline.inspectionTime[1] : null,
      uploadStime: this.formInline.uploadTime ? this.formInline.uploadTime[0] : null,
      uploadEtime: this.formInline.uploadTime ? this.formInline.uploadTime[1] : null,
      projectName: projectNameValue || null, // 使用处理后的项目点名称
      reportStatus: this.formInline.reportStatus,
      isInvalid: this.formInline.isInvalid,
      isPositive: this.formInline.isPositive,
      diagnosis: this.formInline.diagnosis,
      project: "脑卒中",
    };

    console.log("当前搜索条件:", searchParams); // 调试用，确认搜索条件

    // 获取第一页数据并确定总页数
    const firstPage = await this.getUltraSoundData(currentPage, pageSize, searchParams);
    if (!firstPage || !firstPage.data) {
      throw new Error("第一页数据无效或空");
    }
    allItems.push(...firstPage.data);
    totalPages = Math.ceil(firstPage.total / pageSize);

    // 获取其余页的数据
    while (currentPage < totalPages) {
      currentPage++;
      await new Promise(resolve => setTimeout(resolve, 100)); // 延时500ms
      const pageData = await this.getUltraSoundData(currentPage, pageSize, searchParams);
      if (pageData && pageData.data) {
        allItems.push(...pageData.data);
      }
           // 更新进度条，显示分页加载进度
           this.progress = Math.floor((currentPage / totalPages) * 50);
    }

    // 下载和导出数据
    if (allItems.length > 0) {
      await this.downloadAndExportPDFs(allItems); // 执行批量下载
      this.downloadAndExportPDFs(allItems);
      this.restoreDownloadStatus(); // 下载完成后，恢复下载状态
       // 更新所有导出记录的状态为“已下载”
      // allItems.forEach(item => {
      //   item.dwncnt = 1; // 直接设置属性
      // });
      // 将所有已下载的项目 ID 添加到 downloadedItemIds 集合中
      // allItems.forEach(item => {
      //   this.downloadedItemIds.add(item.id); // 假设每个项目都有唯一的 ID
      // });

      // // 重新加载数据以应用下载状态
      // this.loadTableData(searchParams);
    } else {
      this.$message.warning("没有有效报告可供下载");
    }
  } catch (error) {
    console.error("批量导出失败:", error);
    this.$message.error("批量导出失败");
    this.progressStatus = "exception";
  // } finally {
  //   this.progressVisible = false;
  // }
}
},
// async loadTableData(searchParams) {
//   this.tableData = [];
//   const pageSize = 100;
//   let currentPage = 1;
//   let allItems = [];

//   try {
//     const firstPage = await this.getUltraSoundData(currentPage, pageSize, searchParams);
//     if (firstPage && firstPage.data) {
//       allItems.push(...firstPage.data);
//       const totalPages = Math.ceil(firstPage.total / pageSize);

//       while (currentPage < totalPages) {
//         currentPage++;
//         await new Promise(resolve => setTimeout(resolve, 500));
//         const pageData = await this.getUltraSoundData(currentPage, pageSize, searchParams);
//         if (pageData && pageData.data) {
//           allItems.push(...pageData.data);
//         }
//       }

//       // 遍历数据，检查并更新下载状态
//       this.tableData = allItems.map(item => ({
//         ...item,
//         dwncnt: this.downloadedItemIds.has(item.id) ? 1 : item.dwncnt
//       }));
//     }
//   } catch (error) {
//     console.error("加载数据失败:", error);
//   }
// },

// // 执行新查询时重置状态
// async onNewQuery() {
//   this.isBatchDownloaded = false; // 重置批量下载标记
//   const searchParams = { /* 查询参数 */ };
//   await this.loadTableData(searchParams);
// },



// 修改 getUltraSoundData 函数，接受并使用 searchParams
async getUltraSoundData(page, size, searchParams) {
  // 将分页参数和搜索参数传递给 API 请求
  const res = await getUltraSoundList({
    page: page,
    size: size,
    ...searchParams, // 将搜索条件解构为请求参数
  });

  if (res.code === 0) {
    return res;
  } else {
    throw new Error("获取数据失败");
  }
},
// 添加已下载项目到 localStorage
addDownloadedItem(t_sn) {
    const downloadedItems = JSON.parse(localStorage.getItem('downloadedItems')) || [];
    if (!downloadedItems.includes(t_sn)) {
      downloadedItems.push(t_sn);
      localStorage.setItem('downloadedItems', JSON.stringify(downloadedItems));
    }
  },

  // 从 localStorage 恢复下载状态
  restoreDownloadStatus() {
    const downloadedItems = JSON.parse(localStorage.getItem('downloadedItems')) || [];
    this.tableData = this.tableData.map(item => ({
      ...item,
      dwncnt: downloadedItems.includes(item.t_sn) ? 1 : 0
    }));
  },


  },
  // },
};
</script>

